package cqie.frame.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cqie.frame.core.PageParam;
import cqie.frame.entity.*;
import cqie.frame.entity.qo.ClazzCourseTeacherQo;
import cqie.frame.entity.qo.ClazzQo;
import cqie.frame.entity.qo.CourseQo;
import cqie.frame.entity.vo.ClazzCourseTeacherVo;
import cqie.frame.entity.vo.ClazzVo;
import cqie.frame.entity.vo.CourseVo;
import cqie.frame.entity.vo.EmpVo;
import cqie.frame.response.CodeMsg;
import cqie.frame.response.ResultJson;
import cqie.frame.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (ClazzCourseTeacher)表控制层
 *
 * @author makejava
 * @since 2021-09-29 08:50:01
 */
@Api
@RestController
@RequestMapping("/clazzCourseTeacher")
public class ClazzCourseTeacherController {
    /**
     * 服务对象
     */
    @Resource
    private IClazzCourseTeacherService iClazzCourseTeacherService;
    @Resource
    private IClazzService iClazzService;
    @Resource
    private ICourseService iCourseService;
    @Resource
    private IEmpService iEmpService;
    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private IDeptService iDeptService;

    @ApiOperation(value = "新增提交", response = ClazzCourseTeacher.class)
    @PostMapping(value = "/add")
    public ResultJson add(@RequestBody ClazzCourseTeacher po) {
        try {
            //判断重复
            QueryWrapper<ClazzCourseTeacher> qw = new QueryWrapper<>();
            qw.eq("clazzId", po.getClazzId());
            qw.eq("courseId", po.getCourseId());
            qw.eq("teacherId", po.getTeacherId());
            List<ClazzCourseTeacher> find = iClazzCourseTeacherService.list(qw);
            if (find.size() > 0) {
                return ResultJson.error(CodeMsg.CLAZZ_COURSE_TEACHER_ERROR);
            }
            iClazzCourseTeacherService.save(po);
            return ResultJson.success("新增成功");
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    @ApiOperation(value = "删除")
    @GetMapping(value = "/remove")
    public ResultJson remove(Long id) {
        try {
            iClazzCourseTeacherService.removeById(id);
            return ResultJson.success("删除成功");
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    //删除选中课表，多选
    @ApiOperation(value = "删除选中课表", notes = "删除选中课表。")
    @PostMapping(value = "/removeChecked")
    public ResultJson removeChecked(@RequestBody Long[] clazzCourseTeacherIdList) {
        try {
            for (int i = 0; i < clazzCourseTeacherIdList.length; i++) {
                iClazzCourseTeacherService.removeById(clazzCourseTeacherIdList[i]);
            }
            return ResultJson.success("删除成功");
        } catch (Exception e) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    @ApiOperation(value = "修改提交", response = ClazzCourseTeacher.class)
    @PostMapping(value = "/edit")
    public ResultJson edit(@RequestBody ClazzCourseTeacher po) {
        try {

            //判断重复
            QueryWrapper<ClazzCourseTeacher> qw = new QueryWrapper<>();
            qw.eq("clazzId", po.getClazzId());
            qw.eq("courseId", po.getCourseId());
            qw.eq("teacherId", po.getTeacherId());
            qw.ne("id", po.getId()); //排除自己
            List<ClazzCourseTeacher> find = iClazzCourseTeacherService.list(qw);
            if (find.size() > 0) {
                return ResultJson.error(CodeMsg.CLAZZ_COURSE_TEACHER_ERROR);
            }
            iClazzCourseTeacherService.updateById(po);
            return ResultJson.success("修改成功");
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    @ApiOperation(value = "分页列表", response = ClazzCourseTeacherVo.class)
    @PostMapping(value = "/listPaged")
    public ResultJson listPaged(@RequestBody @ApiParam ClazzCourseTeacherQo qo) {
        try {
            Page<ClazzCourseTeacher> page = new Page<>(qo.getPageIndex(), qo.getPageSize());
            //1.查询条件
            QueryWrapper<ClazzCourseTeacher> qw = new QueryWrapper<>();
            if (!StringUtils.isEmpty(qo.getClazzName())) {
                QueryWrapper<Clazz> queryWrapper = new QueryWrapper<>();
                queryWrapper.like("name", qo.getClazzName());
                List<Clazz> clazzList = iClazzService.list(queryWrapper);
                if (clazzList.size() > 0) {
                    List<Long> clazzIdList = new ArrayList<>();
                    clazzList.forEach(x -> {
                        clazzIdList.add(x.getId());
                    });
                    qw.in("clazzId", clazzIdList);
                } else {
                    return ResultJson.error(CodeMsg.CLAZZ_COURSE_TEACHER_NOT_ERROR);
                }
            }
            if (!StringUtils.isEmpty(qo.getTeacherName())) {
                QueryWrapper<Emp> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.like("name", qo.getTeacherName());
                List<Emp> empList = iEmpService.list(queryWrapper1);
                if (empList.size() > 0) {
                    List<Long> teacherIdList = new ArrayList<>();
                    empList.forEach(x -> {
                        teacherIdList.add(x.getId());
                    });
                    qw.in("teacherId", teacherIdList);
                } else {
                    return ResultJson.error(CodeMsg.CLAZZ_COURSE_TEACHER_NOT_ERROR);
                }
            }
            if (!StringUtils.isEmpty(qo.getCourseName())) {
                QueryWrapper<Course> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.like("name", qo.getCourseName());
                List<Course> courseList = iCourseService.list(queryWrapper2);
                if (courseList.size() > 0) {
                    List<Long> courseIdList = new ArrayList<>();
                    courseList.forEach(x -> {
                        courseIdList.add(x.getId());
                    });
                    qw.in("courseId", courseIdList);
                } else {
                    return ResultJson.error(CodeMsg.CLAZZ_COURSE_TEACHER_NOT_ERROR);
                }
            }

            //2.执行查询
            IPage<ClazzCourseTeacher> datas = iClazzCourseTeacherService.page(page, qw);
            //3.生成返回值
            //映射准备--班级
            List<Clazz> allClazz = new ArrayList<>();
            List<Long> idRangeClazz = datas.getRecords().stream().map(ClazzCourseTeacher::getClazzId).collect(Collectors.toList());
            if (idRangeClazz.size() > 0) {
                QueryWrapper<Clazz> qwClazz = new QueryWrapper<>();
                qwClazz.in("id", idRangeClazz);
                allClazz = iClazzService.list(qwClazz);
            }
            //映射准备--课程
            List<Course> allCourse = new ArrayList<>();
            List<Long> idRangeCourse = datas.getRecords().stream().map(ClazzCourseTeacher::getCourseId).collect(Collectors.toList());
            if (idRangeCourse.size() > 0) {
                QueryWrapper<Course> qwCourse = new QueryWrapper<>();
                qwCourse.in("id", idRangeCourse);
                allCourse = iCourseService.list(qwCourse);
            }
            //映射准备--教师
            List<Emp> allTeacher = new ArrayList<>();
            List<Long> idRangeTeacher = datas.getRecords().stream().map(ClazzCourseTeacher::getTeacherId).collect(Collectors.toList());
            if (idRangeTeacher.size() > 0) {
                QueryWrapper<Emp> qwTeacher = new QueryWrapper<>();
                qwTeacher.in("id", idRangeTeacher);
                allTeacher = iEmpService.list(qwTeacher);
            }
            //映射
            List<ClazzCourseTeacherVo> list = new ArrayList<>();
            IPage<ClazzCourseTeacherVo> ret = new Page<>();
            BeanUtils.copyProperties(datas, ret);
            for (ClazzCourseTeacher mo : datas.getRecords()) {
                ClazzCourseTeacherVo vo = new ClazzCourseTeacherVo();
                BeanUtils.copyProperties(mo, vo);
                //映射--班级
                Clazz findClazz = allClazz.stream().filter(x -> x.getId().equals(mo.getClazzId())).findFirst().orElse(null);
                if (findClazz != null) {
                    vo.setClazzName(findClazz.getName());
                }
                //映射--课程
                Course findCourse = allCourse.stream().filter(x -> x.getId().equals(mo.getCourseId())).findFirst().orElse(null);
                if (findCourse != null) {
                    vo.setCourseName(findCourse.getName());
                }
                //映射--教师
                Emp findTeacher = allTeacher.stream().filter(x -> x.getId().equals(mo.getTeacherId())).findFirst().orElse(null);
                if (findTeacher != null) {
                    vo.setTeacherName(findTeacher.getName());
                }
                list.add(vo);
            }
            ret.setRecords(list);
            return ResultJson.success(ret);
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    @ApiOperation(value = "查看详情", response = ClazzCourseTeacherVo.class)
    @GetMapping(value = "/details")
    public ResultJson details(Long id) {
        try {
            //1.获取mo
            ClazzCourseTeacher mo = iClazzCourseTeacherService.getById(id);
            //2.映射成vo
            ClazzCourseTeacherVo vo = new ClazzCourseTeacherVo();
            BeanUtils.copyProperties(mo, vo);
            //映射准备
            //映射--班级
            if (mo.getClazzId() != null) {
                vo.setClazzName(iClazzService.getById(mo.getClazzId()).getName());
            }
            //映射--课程
            if (mo.getCourseId() != null) {
                vo.setCourseName(iCourseService.getById(mo.getCourseId()).getName());
            }
            //映射--教师
            if (mo.getTeacherId() != null) {
                vo.setTeacherName(iEmpService.getById(mo.getTeacherId()).getName());
            }
            //3.返回
            return ResultJson.success(vo);
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }
    @ApiOperation(value = "分页查询班级", notes = "分页表格下拉", response = ClazzVo.class)
    @PostMapping(value = "/qryClazzPaged")
    public ResultJson qryClazzPaged(@RequestBody ClazzQo qo) {
        try {
            Page<Clazz> page = new Page<>(qo.getPageIndex(), qo.getPageSize());
            //1.查询条件
            QueryWrapper<Clazz> qw = new QueryWrapper<>();
            if(StringUtils.isEmpty(qo.getName())==false){
                qw.like("name",qo.getName());
            }
            qw.eq("status",0);
            //2.执行查询
            IPage<Clazz> datas = iClazzService.page(page, qw);
            //3.生成返回值
            //映射
            List<ClazzVo> list = new ArrayList<>();
            IPage<ClazzVo> ret = new Page<>();
            BeanUtils.copyProperties(datas, ret);
            for (Clazz mo : datas.getRecords()) {
                ClazzVo vo = new ClazzVo();
                BeanUtils.copyProperties(mo, vo);
                //映射--状态
                vo.setStatusName(mo.getStatus() == 0 ? "正常" : "禁用");
                list.add(vo);
            }
            ret.setRecords(list);
            return  ResultJson.success(ret);
        } catch (Exception ex) {
            return  ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    @ApiOperation(value = "分页查询课程", notes = "分页表格下拉", response = CourseVo.class)
    @PostMapping(value = "/qryCoursePaged")
    public ResultJson qryCoursePaged(@RequestBody CourseQo qo) {
        try {
            Page<Course> page = new Page<>(qo.getPageIndex(), qo.getPageSize());
            //1.查询条件
            QueryWrapper<Course> qw = new QueryWrapper<>();
            if(StringUtils.isEmpty(qo.getName())==false){
                qw.like("name",qo.getName());
            }
            qw.eq("status",0);
            //2.执行查询
            IPage<Course> datas = iCourseService.page(page, qw);
            //3.生成返回值
            //映射
            List<CourseVo> list = new ArrayList<>();
            IPage<CourseVo> ret = new Page<>();
            BeanUtils.copyProperties(datas, ret);
            for (Course mo : datas.getRecords()) {
                CourseVo vo = new CourseVo();
                BeanUtils.copyProperties(mo, vo);
                //映射--状态
                vo.setStatusName(mo.getStatus() == 0 ? "正常" : "禁用");
                list.add(vo);
            }
            ret.setRecords(list);
            return  ResultJson.success(ret);
        } catch (Exception ex) {
            return  ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }

    @ApiOperation(value = "分页查询员工", notes = "分页表格下拉", response = EmpVo.class)
    @PostMapping(value = "/qryEmpPaged")
    public ResultJson qryEmpPaged(@RequestBody CourseQo qo) {
        try {
            Page<Emp> page = new Page<>(qo.getPageIndex(), qo.getPageSize());
            //1.查询条件
            QueryWrapper<Emp> qw = new QueryWrapper<>();
            if(StringUtils.isEmpty(qo.getName())==false){
                qw.like("name",qo.getName());
            }
            //2.执行查询
            IPage<Emp> datas = iEmpService.page(page, qw);
            //3.生成返回值
            //映射准备--用户
            List<Long> userIdList = datas.getRecords()
                    .stream()
                    .filter(x -> x.getUserId() != null)
                    .map(Emp::getUserId)
                    .distinct()
                    .collect(Collectors.toList());
            List<SysUser> allUser = new ArrayList<>();
            if (userIdList.size() > 0) {
                QueryWrapper<SysUser> qwUser = new QueryWrapper<>();
                qwUser.in("id", userIdList);
                allUser = iSysUserService.list(qwUser);
            }
            //映射准备--所在部门
            List<Long> deptIdList = datas.getRecords()
                    .stream()
                    .filter(x -> x.getDeptId() != null)
                    .map(Emp::getDeptId)
                    .distinct()
                    .collect(Collectors.toList());
            List<Dept> allDept = new ArrayList<>();
            if (deptIdList.size() > 0) {
                QueryWrapper<Dept> qwDept = new QueryWrapper<>();
                qwDept.in("id", deptIdList);
                allDept = iDeptService.list(qwDept);
            }
            //映射
            List<EmpVo> list = new ArrayList<>();
            IPage<EmpVo> ret = new Page<>();
            BeanUtils.copyProperties(datas, ret);
            for (Emp mo : datas.getRecords()) {
                EmpVo vo = new EmpVo();
                BeanUtils.copyProperties(mo, vo);
                //映射--性别
                vo.setSexName(mo.getSex() == 0 ? "男" : "女");
                //映射--登录账号
                if (mo.getUserId() != null) {
                    SysUser findUser = allUser.stream().filter(x -> x.getId().equals(mo.getUserId())).findFirst().orElse(null);
                    if (findUser != null) {
                        vo.setUserAccount(findUser.getAccount());
                    }
                }
                //映射--所在部门
                if (mo.getDeptId() != null) {
                    Dept findDept = allDept.stream().filter(x -> x.getId().equals(mo.getDeptId())).findFirst().orElse(null);
                    if (findDept != null) {
                        vo.setDeptName(findDept.getName());
                    }
                }
                list.add(vo);
            }
            ret.setRecords(list);
            return ResultJson.success(ret);
        } catch (Exception ex) {
            return ResultJson.error(CodeMsg.SERVER_ERROR);
        }
    }
}

